package org.zhaolei.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.zhaolei.enums.AddressStatusEnum;
import org.zhaolei.interceptor.LoginInterceptor;
import org.zhaolei.mapper.AddressMapper;
import org.zhaolei.model.AddressDO;
import org.zhaolei.model.LoginUser;
import org.zhaolei.request.AddressAddRequest;
import org.zhaolei.service.AddressService;
import org.zhaolei.vo.AddressVO;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressMapper addressMapper;

    @Override
    public AddressVO detail(Long id) {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();

        AddressDO addressDO = addressMapper.selectOne(new QueryWrapper<AddressDO>().eq("id", id).eq("user_id", loginUser.getId()));
        //这里不能直接返回DO，要转换成对应的VO类
        if (addressDO == null) {
            return null;
        }
        AddressVO addressVO = new AddressVO();
        BeanUtils.copyProperties(addressDO, addressVO);

        return addressVO;
    }

    /**
     * 新增收货地址
     * @param addressAddRequest
     */
    @Override
    public void add(AddressAddRequest addressAddRequest) {
        //从threadLocal获取登录用户的信息
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        AddressDO addressDO = new AddressDO();
        addressDO.setCreateTime(new Date());
        addressDO.setUserId(loginUser.getId());

        BeanUtils.copyProperties(addressAddRequest, addressDO);

        //确认是否有默认收货地址
        if (addressDO.getDefaultStatus() == AddressStatusEnum.DEFAULT_STATUS.getStatus()) {
            //查找数据库里的默认地址
            AddressDO defaultAddressDO = addressMapper.selectOne(new QueryWrapper<AddressDO>()
                    .eq("user_id", loginUser.getId())
                    .eq("default_status", AddressStatusEnum.DEFAULT_STATUS.getStatus()));
            if (defaultAddressDO != null) {
                //存在默认地址则更新原默认地址为非默认地址
                defaultAddressDO.setDefaultStatus(AddressStatusEnum.COMMON_STATUS.getStatus());
                addressMapper.update(defaultAddressDO, new QueryWrapper<AddressDO>()
                        .eq("user_id", defaultAddressDO.getUserId())); //注意eq（）里面两个字段要统一
            }
        }
        //不管原来是否有默认地址，都直接插入新地址，因为原地址状态已被更改
        int rows = addressMapper.insert(addressDO);

        log.info("新增收货地址：rows={}, data={}", rows, addressDO);
    }

    @Override
    public int del(long addressId) {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();

        return addressMapper.delete(new QueryWrapper<AddressDO>().eq("id", addressId).eq("user_id", loginUser.getId()));
    }

    @Override
    public List<AddressVO> listUserAllAddress() {
        //从threadLocal获取登录用户的信息
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        long user_id = loginUser.getId();

        List<AddressDO> list_DO = addressMapper.selectList(new QueryWrapper<AddressDO>().eq("user_id", user_id));
        //把DO转成VO，lambda流式转换
        List<AddressVO> addressVOList = list_DO.stream().map(obj->{
            AddressVO addressVO = new AddressVO();
            BeanUtils.copyProperties(obj, addressVO);
            return addressVO;
        }).collect(Collectors.toList());

        return addressVOList;
    }
}
